package com.tjec.project.projectWorkbench.controller;

import com.tjec.common.constant.Constants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.framework.interceptor.annotation.RepeatSubmit;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.page.TableDataInfo;
import com.tjec.project.businessWorkbench.service.IBmsBusinessSketchService;
import com.tjec.project.portal.service.IBmsMsgService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsLeaderMember;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsLeaderMemberService;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.projectWorkbench.domain.BmsProjectMemberHistory;
import com.tjec.project.projectWorkbench.domain.BmsProjectStakeholder;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberHistoryService;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.mapper.SysUserRoleMapper;
import com.tjec.project.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 *  项目成员Controller
 *
 * @author tjec
 * @date 2020-04-14
 */
@Api(value = "项目主页-项目成员接口" , tags = {"项目主页-项目成员接口"})
@RestController
@RequestMapping("/project/member")
public class BmsProjectMemberController extends BaseController {

    @Autowired
    private IBmsProjectMemberService bmsProjectMemberService;

    @Autowired
    private IBmsProjectService bmsProjectService;

    @Autowired
    private IBmsProjectMemberHistoryService iBmsProjectMemberHistoryService;

    @Autowired
    private IBmsLeaderMemberService bmsLeaderMemberService;

    @Autowired
    private ISysUserService userService;
    
    @Autowired
    private IBmsBusinessSketchService businessSketchService;

    /**
     * 查询项目成员列表
     */
    @ApiOperation("查询项目成员列表")
//    @PreAuthorize("@ss.hasPermi('project:member:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsProjectMember bmsProjectMember)
    {
        startPage();
        List<BmsProjectMember> list = bmsProjectMemberService.selectBmsProjectMemberList(bmsProjectMember);
        for (BmsProjectMember projectMember : list) {
            projectMember.setProjectName(String.valueOf(bmsProjectMemberService.selectBmsProjectMemberByUserId(projectMember.getUserId())));
        }
        return getDataTable(list);
    }
    
    /**
     * 查询项目成员列表
     */
    @ApiOperation("查询项目成员列表包含项目负责人")
//    @PreAuthorize("@ss.hasPermi('project:member:list')")
    @GetMapping("/allList")
    public TableDataInfo allList(BmsProjectMember bmsProjectMember)
    {
        startPage();
        SysUser user = new SysUser();
        if(bmsProjectMember.getBusinessId()!=null && !"".equals(bmsProjectMember.getBusinessId())) {
        	user = businessSketchService.getProjectLeader(bmsProjectMember.getBusinessId());
        }
        
        if(user!=null) {
        	
        	List<BmsProjectMember> list = bmsProjectMemberService.selectBmsProjectMemberList(bmsProjectMember);
        	int isExist=0;
            for (BmsProjectMember projectMember : list) {
            	if(user.getUserId().equals(projectMember.getUserId())) {
            		isExist = 1;
            	}
                projectMember.setProjectName(String.valueOf(bmsProjectMemberService.selectBmsProjectMemberByUserId(projectMember.getUserId())));
            }
            if(isExist==0) {
            	BmsProjectMember member = new BmsProjectMember();
            	member.setUserId(user.getUserId());
            	member.setNickName(user.getNickName());
            	list.add(member);
            }
            
            return getDataTable(list);
            
        }else {
        	List<BmsProjectMember> list = new ArrayList<BmsProjectMember>();
            return getDataTable(list);
        }
        
    }

    /**
     * 添加项目成员列表
     */
    @ApiOperation("添加项目成员列表")
//    @PreAuthorize("@ss.hasPermi('project:member:addList')")
    @GetMapping("/addList")
    public TableDataInfo addList(BmsProjectMember bmsProjectMember)
    {
        List<BmsProjectMember> list = new ArrayList<>();
        BmsProject bmsProject = bmsProjectService.selectBmsProjectByGuid(bmsProjectMember.getProjectId());
        if(null!=bmsProject){
            SysUser projectLeaderUser = userService.findSysuUserByProjectLeaderNo(bmsProject.getProjectLeaderNo());
            bmsProjectMember.setUserId(projectLeaderUser.getUserId());
            startPage();
            list = bmsProjectMemberService.selectBmsProjectMemberNoProjectMember(bmsProjectMember);
            for (BmsProjectMember projectMember : list) {
                projectMember.setProjectName(String.valueOf(bmsProjectMemberService.selectBmsProjectMemberByUserId(projectMember.getUserId())));
                projectMember.setProjectId(bmsProjectMember.getProjectId());
                //新增时默认添加为项目成员
                projectMember.setRole("1");
            }
        }
        /*List<BmsProjectMember> bmsProjectMembers = new ArrayList<>();
        BmsProject bmsProject = bmsProjectService.selectBmsProjectByGuid(bmsProjectMember.getProjectId());
        if(null!=bmsProject){
            BmsLeaderMember bmsLeaderMember = new BmsLeaderMember();
            SysUser projectLeaderUser = userService.findSysuUserByProjectLeaderNo(bmsProject.getProjectLeaderNo());
            bmsLeaderMember.setLeader(projectLeaderUser.getUserId());
            bmsLeaderMember.setProjectId(bmsProjectMember.getProjectId());
            bmsLeaderMember.setNickName(bmsProjectMember.getNickName());
            bmsLeaderMember.setSortBy(bmsProjectMember.getSortBy());
            bmsLeaderMember.setOrder(bmsProjectMember.getOrder());
            startPage();
            List<BmsLeaderMember> list = bmsLeaderMemberService.selectBmsLeaderMemberNoProjectMember(bmsLeaderMember);
            for (BmsLeaderMember leaderMember : list) {
                BmsProjectMember projectMember = new BmsProjectMember();
                projectMember.setUserId(leaderMember.getUserId());
                projectMember.setProjectId(bmsProjectMember.getProjectId());
                SysUser user = userService.selectUserById(leaderMember.getUserId());
                if(user!=null){
                    projectMember.setNickName(user.getNickName());
                    projectMember.setJobNo(user.getJobNo());
                    projectMember.setPhonenumber(user.getPhonenumber());
                    projectMember.setStatus(user.getStatus());
                }
                projectMember.setProjectName(String.valueOf(bmsProjectMemberService.selectBmsProjectMemberByUserId(leaderMember.getUserId())));
                projectMember.setRole("1");
                bmsProjectMembers.add(projectMember);
            }
        }*/
        return getDataTable(list);
    }

    /**
     * 获取项目成员详细信息
     */
    @ApiOperation("获取项目成员详细信息")
    @ApiImplicitParam(name = "guid", value = "项目成员guid", required = true, dataType = "String", paramType = "path")
//    @PreAuthorize("@ss.hasPermi('project:member:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid)
    {
        return AjaxResult.success(bmsProjectMemberService.selectBmsProjectMemberByGuid(guid));
    }

    /**
     * 新增项目成员
     */
    @ApiOperation("新增项目成员")
    @ApiImplicitParam(name = "bmsProjectMember", value = "新增项目成员", dataType = "BmsProjectMember")
//    @PreAuthorize("@ss.hasPermi('project:member:add')")
    @Log(title = "项目成员", businessType = BusinessType.INSERT)
//    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody BmsProjectMember bmsProjectMember)
    {
        //查询是否重复添加项目成员
        boolean repeatFlag = bmsProjectMemberService.repeatBmsProjectMember(bmsProjectMember.getProjectId(), bmsProjectMember.getUserId());
        if(repeatFlag){
            return AjaxResult.error("新增项目成员已存在");
        }else{
            bmsProjectMember.setJoinTime(DateUtils.getNowDate());
            return toAjax(bmsProjectMemberService.insertBmsProjectMember(bmsProjectMember));
        }
    }

    /**
     * 修改项目成员
     */
    @ApiOperation("修改项目成员")
    @ApiImplicitParam(name = "bmsProjectMember", value = "修改项目成员", dataType = "BmsProjectMember")
//    @PreAuthorize("@ss.hasPermi('project:member:edit')")
    @Log(title = "项目成员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BmsProjectMember bmsProjectMember)
    {
        return toAjax(bmsProjectMemberService.updateBmsProjectMember(bmsProjectMember));
    }

    /**
     * 删除项目成员
     */
    @ApiOperation("删除项目成员")
    @ApiImplicitParam(name = "guids", value = "项目成员guid", required = true, dataType = "Array", paramType = "path")
//    @PreAuthorize("@ss.hasPermi('project:member:remove')")
    @Log(title = "项目成员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{guids}/{type}")
    public AjaxResult remove(@PathVariable String[] guids, @PathVariable String type)throws Exception
    {
        return toAjax(bmsProjectMemberService.deleteBmsProjectMemberByGuids(guids, type));
    }

    /**
     * 历史成员变更记录
     * @param bmsProjectMemberHistory
     * @return
     */
    @ApiOperation("项目成员历史成员变更记录")
//    @PreAuthorize("@ss.hasPermi('project:member:historyList')")
    @GetMapping("/historyList")
    public TableDataInfo historyList(BmsProjectMemberHistory bmsProjectMemberHistory)
    {
        startPage();
        List<BmsProjectMemberHistory> list = iBmsProjectMemberHistoryService.selectBmsProjectMemberHistoryList(bmsProjectMemberHistory);
        return getDataTable(list);
    }

    /**
     * 添加历史成员变更记录，供项目成员添加、修改、删除记录
     * @param bmsProjectMemberHistory
     * @return
     */
    @ApiOperation("添加历史成员变更记录，供项目成员添加、修改、删除记录")
    @ApiImplicitParam(name = "bmsProjectMemberHistory", value = "添加历史成员变更记录", dataType = "BmsProjectMemberHistory")
    @Log(title = "添加历史成员变更记录", businessType = BusinessType.INSERT)
//    @PreAuthorize("@ss.hasPermi('project:member:addHistory')")
    @PostMapping("/addHistory")
    public AjaxResult addHistory(@RequestBody BmsProjectMemberHistory bmsProjectMemberHistory)
    {
        return toAjax(iBmsProjectMemberHistoryService.insertBmsProjectMemberHistory(bmsProjectMemberHistory));
    }
}
